package com.firewolf.hibernate.relationship.many_one_both.main;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.firewolf.hibernate.relationship.many_one_both.dto.Customer;
import com.firewolf.hibernate.relationship.many_one_both.dto.Order;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;


	/**
	 * @Description:
	 	使用PropertyNamesFilter的时候，关闭session 的时候会抛出异常，解决办法有两种：
	 	1.不关闭session（不推荐）
	 	2.在Customer的set上设置lazy="false"，直接加载出orders
	 * @输入和输出示例：
	 * @思路：
	 */
	@Test
	public void testMany2OneBothGet2() {
		openSession();//打开session

		String hql = "from Customer";
		Query qry = session.createQuery(hql);
		List list = qry.list();
		
		//SimplePropertyFilter filter = new SimplePropertyFilter();
		PropertyNamesFilter filter1 = new PropertyNamesFilter("customer");
		closeSession();//关闭session
		
		//这里应该是返回到dao层，一直返回到Action，然后转成json,为了方便，直接写在这里
		String json = JSONObject.toJSONString(list,filter1,SerializerFeature.DisableCircularReferenceDetect);
		System.out.println(json);

	}

	/**
	 * @Description: 保存的时候，插入的顺序会影响SQL语句的条数 @输入和输出示例： @思路：
	 */
	@Test
	public void testMany2OneBothSave() {
		openSession();

		Customer customer = new Customer();
		customer.setCustomerName("AAAA");

		Order order1 = new Order();
		order1.setOrderName("ORDER-111");

		Order order2 = new Order();
		order2.setOrderName("ORDER-222");

		// 设定关联关系
		order1.setCustomer(customer);
		order2.setCustomer(customer);

		// 设置一的一端的关联关系
		customer.getOrders().add(order1);
		customer.getOrders().add(order2);

		// 先插入 Customer, 再插入 Order, 3 条 INSERT, 2 条 UPDATE
		session.save(customer);
		session.save(order1);
		session.save(order2);

		// 先插入 Order, 再插入 Cusomer, 3 条 INSERT, 4 条 UPDATE
		// session.save(order1);
		// session.save(order2);
		// session.save(customer);

		closeSession();
	}

	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}

	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("many_one_both.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
